<template>
    <view class="container">
        <z-paging
            ref="paging"
            :scroll-with-animation="true"
        >
            <!-- 骨架屏区域开始 -->
            <uv-skeletons :loading="isSkeleton" :skeleton="skeletons"></uv-skeletons>
            <!-- 骨架屏区域结束 -->

            <template #top>
                <!-- 自定义导航区域开始 -->
                <TridentNavBar>
                    <template #left>
                        <!-- #ifdef MP-ALIPAY -->
                        <i class="iconfont icon-zuojiantou" style="font-size: 36rpx;font-weight: bold"></i>
                        <!-- #else -->
                        <i class="iconfont icon-zuojiantou" style="font-size: 36rpx;"></i>
                        <!-- #endif -->
                    </template>
                    <template #default>选择联系人</template>
                    <template #right >
                        <text style="border: 2rpx solid #fff;padding: 4rpx 15rpx;border-radius: 5rpx;" @click="handleJoinGroupChat">完 成</text>
                    </template>
                </TridentNavBar>
                <!-- 自定义导航区域结束 -->

                <!-- 搜索区域开始 -->
                <TridentSearch @search="handleSearch"/>
                <!-- 搜索区域结束 -->
            </template>

            <!-- 列表区域开始 -->
            <uv-index-list
                :index-list="Object.keys(contactList)"
                :activeColor="global.THEME_COLOR"
                customNavHeight="160rpx"
            >
                <template v-for="(item, index) in contactList">
                    <uv-index-item>
                        <uv-index-anchor
                            :text="index"
                            bgColor="#e2f8f3"
                            customNavHeight="50"
                        />
                        <view class="contact-wrap">
                            <TridentFriendItem v-for="(friend, index) in item" :friend="friend" :key="index" :isShowCheck="true"  @click="handleChange(friend)"/>
                        </view>
                    </uv-index-item>
                </template>
            </uv-index-list>
            <!-- 列表区域结束 -->
        </z-paging>
    </view>
</template>

<script lang="ts" setup>
import { reqFriendListAPI } from '@/apis/friend'
import { reqGroupChatDetailAPI, reqJoinGroupChatAPI } from '@/apis/groupChat'
import type { FriendListParams } from '@/types/friend'
import type { GroupChat, JoinGroupChatParams } from '@/types/groupChat'
import { pinyin } from 'pinyin-pro'
import { inject, reactive, ref } from 'vue'
import { goto } from '@/utils/tools'
import { onShow } from '@dcloudio/uni-app'


// --------------- 定义全局变量开始 ---------------
// 全局属性
const global: any = inject('global')

// 获取页面参数
const query = defineProps({
    "gid": {
        type: String,
        default: '0'
    }
})

// 联系人
const contactList: any = ref({})
// --------------- 定义全局变量结束 ---------------



onShow(async () => {
    for (let index = 0; index < 12; index++) {
        skeletons.push(skeleton as never)
    }

    await getGroupChatInfo()
    await getContactList()
})



// -------------- 处理复选框变化开始 --------------
const handleChange = (friend: any) => {
    if (friend.disabled) {
        return false
    }

    friend.is_check = !friend.is_check
    
    let uids = joinGroupChatParams.value.uids ? joinGroupChatParams.value.uids.split(',') : []

    if (friend.is_check == true) {
        uids.push(friend.info.uid)
    } else {
        const index = uids.findIndex(item => item == friend.info.uid)
        uids.splice(index, 1)
    }

    joinGroupChatParams.value.uids = uids.join()
}
// -------------- 处理复选框变化结束 --------------



// -------------- 处理联系人列表开始 --------------
const params = ref<FriendListParams>({
    username: '',
    is_my_friend: 1,
    is_friend_info: 1,
    status: '1',
    page: 1,
    page_size: -1
})

// 获取联系人列表
const getContactList = async () => {
    // 显示骨架屏
    isSkeleton.value = true

    const result = await reqFriendListAPI(params.value)
    let tempFriendList: any = {}
    result.data.friends.forEach(item => {
        item.is_check = false
        item.disabled = false
        // 判断当前联系人列表中是否存在群聊成员
        groupChat.value?.member.forEach(member => {
            if (item.info.uid == member.uid) {
                item.is_check = true
                item.disabled = true
            }
        });
        let initial = pinyin(item.info.username, {pattern: 'first', toneType: 'none' }).substr(0, 1).toLocaleUpperCase()
        
        if (!tempFriendList[initial]) {
            tempFriendList[initial] = []
        }

        tempFriendList[initial].push(item)
    })

    contactList.value = Object.keys(tempFriendList).sort().reduce((acc: any, key) => {
        acc[key] = tempFriendList[key];
        return acc;
    }, {});

    // 隐藏骨架屏
    isSkeleton.value = false
}
// -------------- 处理联系人列表结束 --------------



// --------------- 处理群聊信息开始 ---------------
// 群聊信息
const groupChat = ref<GroupChat>()

// 获取群聊信息
const getGroupChatInfo = async () => {
    const result = await reqGroupChatDetailAPI(query.gid as never)
    groupChat.value = result.data
}
// --------------- 处理群聊信息结束 ---------------



// -------------- 处理搜索联系人开始 --------------
// 搜索联系人
const handleSearch = (e: any) => {
    params.value.username = e.keyword.value
    getContactList()
}
// -------------- 处理搜索联系人结束 --------------



// --------------- 处理加入群聊开始 ---------------
const joinGroupChatParams = ref<JoinGroupChatParams>({
    gid: query.gid as never,
    uids: '',
    network: 'ws'
})

// 加入群聊
const handleJoinGroupChat = async () => {
    if (joinGroupChatParams.value.uids == '') {
        uni.showToast({
            title: '请选择联系人',
            duration: 1000,
            icon: 'none'
        })

        return false
    }
    await reqJoinGroupChatAPI(joinGroupChatParams.value)
    uni.showToast({
        title: '加入群聊成功',
        duration: 1000
    })

    setTimeout(() => {
        goto('/pagesChat/info/index?mode=2&gid=' + query.gid)
    }, 1000)
}
// --------------- 处理加入群聊结束 ---------------



// --------------- 定义骨架变量开始 ---------------
// 定义是否显示骨架
const isSkeleton = ref(false)

// 定义骨架参数
const skeleton = reactive({
  type: 'flex',
  num: 1,
  style: 'padding: 15rpx 30rpx 15rpx 25rpx;background-color: #fff;border-bottom: 2rpx solid #f6f6f6;align-items: center;',
  children: [
    // 选择框区域
    {
      type: 'custom',
      num: 1,
      style: 'width: 42rpx;height: 42rpx;border-radius: 21rpx;margin-right: 20rpx;'
    },

    // 图片区域
    {
      type: 'custom',
      num: 1,
      style: 'width: 90rpx;height: 90rpx;border-radius: 10rpx;margin-right: 20rpx;'
    },

    {
      type: 'custom',
      num: 1,
      style: ['width: 180rpx;height: 40rpx;']
    }
  ]
})

const skeletons = reactive([])
// --------------- 定义骨架变量结束 ---------------
</script>

<style scoped lang="scss">
.container {
    .contact-wrap {
        padding-left: 30rpx;
        background-color: #fff;
    }
}
</style>